﻿/*
Copyright (c) 2008, ThaoNguyen. All rights reserved.
*/
/**
 * The NTTHAO form validator is a generic validator for form submit event.
 * @module formValidator
 * @namespace NTTHAO.formValidator
 */
NTTHAO.formValidator = NTTHAO.formValidator || {};

NTTHAO.formValidator.validatorList = new Array();

NTTHAO.formValidator.onFormSubmit = function() {
    
    var validateResult = true;
    var arr = NTTHAO.formValidator.validatorList;
    var firstFocus = true;
    
    for (i = 0; i < arr.length; i++) {
        try {
            var val = {};
            var args = {};
            var objValidate = arr[i];

            val.controltovalidate = objValidate.ctrlToValidate;
            args.IsValid = true;
            
            var func = objValidate.validateFunction;
            
            func.apply(val.controltovalidate, [val, args]);
            if (args.IsValid) {
                //NTTHAO.util.getElement(objValidate.ctrlToDisplayMessage).style.visibility = "hidden";
                NTTHAO.util.getElement(objValidate.ctrlToDisplayMessage).style.display = "none";
            } else {
                if (firstFocus) {
                    firstFocus = false;
                    NTTHAO.util.getElement(objValidate.ctrlToValidate).focus();
                    NTTHAO.util.getElement(objValidate.ctrlToValidate).select()
                }
                //NTTHAO.util.getElement(objValidate.ctrlToDisplayMessage).style.visibility = "";
                NTTHAO.util.getElement(objValidate.ctrlToDisplayMessage).style.display = "inline";
                validateResult = false;
            }
        } catch (ex) {
        }
    }
    
    return validateResult;
}

NTTHAO.formValidator.validate = function(form, input, validate, func) {
    try {
        form.onsubmit = NTTHAO.formValidator.onFormSubmit;
        var ctrlToDisplayMessage = NTTHAO.util.getElement(validate);
        ctrlToDisplayMessage.style.visibility = "hidden";

        var obj = {};
        obj.ctrlToValidate = input;
        obj.ctrlToDisplayMessage = validate;
        obj.validateFunction = func;

        NTTHAO.formValidator.validatorList[NTTHAO.formValidator.validatorList.length] = obj;
    } catch (ex) {}    
}

